package org.elephantt.webby.example;

import org.elephantt.webby.*;

import java.io.IOException;

public class ExampleApplication extends SimpleHttpApplication {
  public RequestMapper createRequestMapper() {
    RouteRequestMapper mapper = new RouteRequestMapper();
    SiteController siteController = new SiteController();
    mapper.addRoute(HttpMethod.GET, "/", siteController, "home");
    mapper.addRoute(HttpMethod.GET, "/person/:urlname", siteController, "person");
    mapper.addRoute(HttpMethod.POST, "/create_person", siteController, "createPerson");
    mapper.addRoute(HttpMethod.GET, "/info", siteController, "info");
    mapper.addResourceRoute("/article/:urlname", new ArticleController(), "urlname");
    return mapper;
  }

  public static class SiteController {
    public String home() {
      return "<html><form method='POST' action='/person/new'>name: <input name='urlname'/><input type='submit'/></form></html>";
    }

    public FtlView person(Request request) {
      return new FtlView("person.ftl", Model.create().append("name", request.getUrlParameter("urlname")));
    }

    public Object createPerson(Request request) {
      return new Redirect("/person/" + request.getParameter("urlname"));
    }

    public void info(Request request, Response response) throws IOException {
      response.setContentType("text/plain");
      response.getWriter().println("request URI: " + request.getRequestURI());
    }
  }

  public static class ArticleController {
    public String get(Request request) {
      return "you got " + request.getUrlParameter("urlname");
    }

    public Redirect post(Request request) {
      return new Redirect("/person/" + request.getParameter("urlname"));
    }
  }

  public static void main(String[] args) throws Exception {
    (new ExampleApplication()).startAndJoin();
  }
}